package com.sample.plove.authener.server.impl;

import com.sample.plove.authener.config.PropertiesUtils;
import com.sample.plove.authener.config.WechatConfig;
import com.sample.plove.authener.config.WechatPropertiesConstant;
import com.sample.plove.authener.model.BasicAuthParam;
import com.sample.plove.authener.model.ResultState;
import com.sample.plove.authener.model.response.AccessToken;
import com.sample.plove.authener.model.response.AuthAccessToken;
import com.sample.plove.authener.model.response.AuthUserInfo;
import com.sample.plove.authener.server.WechatAuthService;
import com.sample.plove.authener.util.HttpUtil;
import com.sample.plove.authener.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * PackageName:com.sample.plover.server.impl
 * Author:Administrator
 * Time:0:36
 * Date:2019/5/14
 * Describe:
 */
@Repository
@Slf4j
public class WechatAuthServiceImpl implements WechatAuthService {
    /**
     * 获取授权凭证token
     *
     * @return 授权凭证token
     */
    @Override
    public AccessToken getAccessToken() {
        String token = (String) PropertiesUtils.getCommonYml(WechatPropertiesConstant.WECHAT_TOKEN);
        if (token == null || token.equals("")) {
            Map<String, String> map = new TreeMap<>();
            map.put("appid", WechatConfig.APP_ID);
            map.put("secret", WechatConfig.APP_SECRET);
            map.put("grant_type", "client_credential");
            String json = HttpUtil.doGet(WechatConfig.GET_ACCESS_TOKEN_URL, map);
            AccessToken bean = JsonUtil.fromJson(json, AccessToken.class);
            if (bean != null) {
                System.out.println(bean.toString());
                return bean;
            }
        } else {
            return null;
        }
        return null;
    }

    /**
     * 获取授权请求url
     *
     * @param basic
     * @param url
     * @return
     */
    @Override
    public String getAuthUrl(BasicAuthParam basic, String url) {
        Map<String, String> params = basic.getParams();
        try {
            return HttpUtil.setParams(url, params, "") + "#wechat_redirect";
        } catch (Exception e) {
            log.debug("error", e.getMessage());
        }
        return null;
    }

    /**
     * 获取网页授权凭证
     *
     * @param basic
     * @param url
     * @return
     */
    @Override
    public AuthAccessToken getAuthAccessToken(BasicAuthParam basic, String url) {
        try {
            String result = HttpUtil.doGet(url, basic.getParams());
            return JsonUtil.fromJson(result, AuthAccessToken.class);
        } catch (Exception e) {
            log.debug("error", e.getMessage());
        }
        return null;
    }

    /**
     * 刷新网页授权凭证
     *
     * @param basic 参数
     * @param url   请求路径
     * @return 新的网页授权凭证
     */
    @Override
    public AuthAccessToken refreshAuthAccessToken(BasicAuthParam basic, String url) {
        try {
            String result = HttpUtil.doGet((String) PropertiesUtils.getCommonYml(WechatPropertiesConstant.REFRESH_AUTH_OAUTH_URL), basic.getParams());
            return JsonUtil.fromJson(result, AuthAccessToken.class);
        } catch (Exception e) {
            log.debug("error", e.getMessage());
        }
        return null;
    }

    /**
     * 通过网页授权获取用户信息
     *
     * @param accessToken 网页授权接口调用凭证
     * @param openid      用户唯一标识
     * @return
     */
    @Override
    public AuthUserInfo getAuthUserInfo(String accessToken, String openid) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", accessToken);
        params.put("open_id", openid);
        params.put("lang","zh_CN");
        String result = HttpUtil.doGet(WechatConfig.SNS_USERINFO_URL, params);
        try {
            log.info("getAuthUserInfo",result);
            return JsonUtil.fromJson(result, AuthUserInfo.class);
        } catch (Exception e) {
            log.debug("error", e.getMessage());
        }
        return null;
    }

    /**
     * 校验授权凭证access_token是否有效
     * @param accessToken 网页授权接口调用凭证
     * @param openid      用户唯一标识
     * @return { "errcode":0,"errmsg":"ok"}表示成功 { "errcode":40003,"errmsg":"invalid openid"}失败
     */
    @Override
    public ResultState authToken(String accessToken, String openid) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", accessToken);
        params.put("open_id", openid);
        String result = HttpUtil.doGet((String) PropertiesUtils.getCommonYml(WechatPropertiesConstant.CHECK_AUTH_STATUS_URL), params);
        try {
            return JsonUtil.fromJson(result, ResultState.class);
        } catch (Exception e) {
            log.debug("error", e.getMessage());
        }
        return null;
    }
}
